package com.project.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 线程类
 */
public class SocketThread implements Runnable {
    private static String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";
    private Socket socket;

    public SocketThread(Socket socket) {
        this.socket = socket;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            //从socket中得到读取流，用于接收客户端发送的数据
            InputStream in = socket.getInputStream();
            //从socket中得到写入流，用于将数据发送到客户端
            OutputStream out = socket.getOutputStream();
            //将写入流封装成response对象，便于更好地发送数据
            Response response = new Response(out);
            //将读取流封装成request对象，便于更好地读取请求信息
            Request request = new Request(in);

            System.out.println(request);
            //将数据发送给客户端
            out.write(header.getBytes());
            String url = request.getUrl();
            response.sendFile(url);
            //刷新流
            out.flush();
            //关闭流
            in.close();
            out.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
